package top.wshape1.shiziapi.project.controller;

import jakarta.annotation.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import top.wshape1.shiziapi.common.constant.AuthConstant;
import top.wshape1.shiziapi.common.domain.CommonUser;
import top.wshape1.shiziapi.common.utils.Base64Util;
import top.wshape1.shiziapi.common.utils.R;
import top.wshape1.shiziapi.project.service.LikeService;

import java.util.List;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2023-11-20
 */

@RestController
@RequestMapping("/like")
public class LikeController {

    @Resource
    private LikeService likeService;

    /*
    先存到redis, 定时从redis转存到mysql
    使用set       project:like:{projectId} -> {userId}         点赞列表
       set      project:note:like:{projectId} -> {userId}    记录要持久化的 like
       set      project:note:unlike:{projectId} -> {userId}  记录要持久化的 unlike
     */

    /**
     * 点赞数
     *
     * @param projectId
     * @return
     */
    @GetMapping("/count/{projectId}")
    public R<Long> count(@PathVariable Long projectId) {

        long count = likeService.countLike(projectId);

        return R.ok(count);
    }

    /**
     * 点赞
     *
     * @param projectId
     * @return
     */
    @PostMapping("/like/{projectId}")
    public R<Void> like(@PathVariable Long projectId,
                        @RequestHeader(AuthConstant.HEADER_PAYLOAD_NAME) String userBase64) {

        CommonUser commonUser = Base64Util.decodeAndParse(userBase64, CommonUser.class);

        likeService.like(projectId, commonUser.getId());

        return R.ok();
    }

    /**
     * 取消点赞
     *
     * @param projectId
     * @return
     */
    @PostMapping("/unlike/{projectId}")
    public R<Void> unlike(@PathVariable Long projectId,
                          @RequestHeader(AuthConstant.HEADER_PAYLOAD_NAME) String userBase64) {

        CommonUser commonUser = Base64Util.decodeAndParse(userBase64, CommonUser.class);

        likeService.unlike(projectId, commonUser.getId());

        return R.ok();
    }

    @PostMapping("/isLike")
    public R<List<Boolean>> isLike(@RequestBody List<Long> projectIdList,
                                   @RequestHeader(value = AuthConstant.HEADER_PAYLOAD_NAME, required = false) String userBase64) {

        if (!StringUtils.hasLength(userBase64)) {
            return R.ok(List.of());
        }

        CommonUser commonUser = Base64Util.decodeAndParse(userBase64, CommonUser.class);

        List<Boolean> isLike = likeService.isLike(projectIdList, commonUser.getId());

        return R.ok(isLike);
    }

}
